import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  BadRequestException,
  Logger
} from '@nestjs/common';
import { TestService } from './test.service';
import { IsString, IsNotEmpty } from 'class-validator';

class TestShareLinkDto {
  @IsString()
  @IsNotEmpty({ message: '分享链接不能为空' })
  shareUrl: string;
}

@Controller('test')
export class TestController {
  private readonly logger = new Logger(TestController.name);

  constructor(private testService: TestService) {}

  @Post('share-link')
  @HttpCode(HttpStatus.OK)
  async testShareLink(@Body() testDto: TestShareLinkDto) {
    try {
      this.logger.log(`收到分享链接测试请求: ${testDto.shareUrl.substring(0, 100)}...`);

      // 基本URL格式验证
      if (!testDto.shareUrl.startsWith('http')) {
        throw new BadRequestException('分享链接格式不正确');
      }

      const result = await this.testService.testShareLink(testDto.shareUrl);

      return {
        success: result.success,
        message: result.success ? '测试完成' : '测试失败',
        data: result.testResults,
        summary: result.summary,
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error(`测试分享链接时发生错误: ${error.message}`);

      return {
        success: false,
        message: '测试过程中发生错误',
        error: error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Post('accessibility')
  @HttpCode(HttpStatus.OK)
  async testAccessibility(@Body() testDto: TestShareLinkDto) {
    try {
      this.logger.log(`收到链接可访问性测试请求: ${testDto.shareUrl.substring(0, 100)}...`);

      const result = await this.testService.testLinkAccessibility(testDto.shareUrl);

      return {
        success: result.status === 'success',
        message: result.status === 'success' ? '链接可访问' : '链接不可访问',
        data: result,
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error(`测试链接可访问性时发生错误: ${error.message}`);

      return {
        success: false,
        message: '测试过程中发生错误',
        error: error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }
}